package com.liuyucheng.util;

import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileNameEncoder {
    public static void main(String[] args) {
        Set<String> set1 = new HashSet<String>();
        Set<String> set2 = new HashSet<String>();

        set1.add("1");
        set1.add("2");
        set1.add("3");

        set2.add("2");

//        set1.removeAll(set2);
        Set<String> intersection = new HashSet<>(set1); // 复制set1，避免修改原集合
        intersection.retainAll(set2); // 保留与set2共有的元素

        System.out.println("intersection = " + intersection);
        System.out.println("set1 = " + set1);
    }

    /**
     * 将包含八进制转义序列（如\350）的字符串转换为正常显示的字符串
     *
     * @param input 包含八进制转义的字符串
     * @return 转换后的字符串
     */
    public static String decodeOctalEscape(String input) {
        // 正则表达式匹配八进制转义序列（\ followed by 3 digits）
        Pattern pattern = Pattern.compile("\\\\(\\d{3})");
        Matcher matcher = pattern.matcher(input);

        // 用于存储解析后的字节
        byte[] bytes = new byte[input.length()];
        int byteIndex = 0;

        int lastEnd = 0;
        while (matcher.find()) {
            // 添加非转义部分的字符
            String nonEscapePart = input.substring(lastEnd, matcher.start());
            for (char c : nonEscapePart.toCharArray()) {
                bytes[byteIndex++] = (byte) c;
            }

            // 解析八进制数字为字节
            String octalStr = matcher.group(1);
            int octalValue = Integer.parseInt(octalStr, 8);
            bytes[byteIndex++] = (byte) octalValue;

            lastEnd = matcher.end();
        }

        // 添加剩余的非转义部分
        String remainingPart = input.substring(lastEnd);
        for (char c : remainingPart.toCharArray()) {
            bytes[byteIndex++] = (byte) c;
        }

        // 截取有效字节并按UTF-8编码转换为字符串
        byte[] validBytes = new byte[byteIndex];
        System.arraycopy(bytes, 0, validBytes, 0, byteIndex);
        return new String(validBytes, StandardCharsets.UTF_8);
    }
}
